package com.example.capsule.controller;

import com.example.capsule.service.SmsService;
import com.example.capsule.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/auth")
@Tag(name = "认证API", description = "手机号验证码登录接口")
public class AuthController {
    private static final Logger logger = LoggerFactory.getLogger(AuthController.class);

    private final SmsService smsService;
    private final UserService userService;

    public AuthController(SmsService smsService, UserService userService) {
        this.smsService = smsService;
        this.userService = userService;
    }

    @GetMapping("/validate-token")
    @Operation(summary = "验证Token有效性", description = "验证JWT token是否有效")
    public ResponseEntity<Map<String, Object>> validateToken(@RequestHeader("Authorization") String authHeader) {
        Map<String, Object> response = new HashMap<>();

        try {
            if (authHeader != null && authHeader.startsWith("Bearer ")) {
                String token = authHeader.substring(7);
                boolean isValid = userService.validateToken(token);

                response.put("success", isValid);
                response.put("message", isValid ? "Token有效" : "Token无效");
                return ResponseEntity.ok(response);
            }

            response.put("success", false);
            response.put("message", "未提供Token");
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);

        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "Token验证失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    @PostMapping("/send-code")
    @Operation(summary = "发送验证码", description = "向指定手机号发送验证码短信")
    public ResponseEntity<Map<String, Object>> sendVerificationCode(
            @RequestParam String phone) {

        logger.info("收到发送验证码请求: {}", phone);
        Map<String, Object> response = new HashMap<>();

        try {
            if (!smsService.isValidPhone(phone)) {
                response.put("success", false);
                response.put("message", "手机号格式不正确");
                logger.warn("手机号格式验证失败: {}", phone);
                return ResponseEntity.badRequest().body(response);
            }

            // 检查发送频率
            if (!smsService.canSendCode(phone)) {
                long nextTime = smsService.getNextSendTime(phone);
                response.put("success", false);
                response.put("message", "发送过于频繁，请" + nextTime + "秒后再试");
                response.put("nextSendTime", nextTime);
                logger.warn("发送频率限制: {}", phone);
                return ResponseEntity.badRequest().body(response);
            }

            boolean success = smsService.sendVerificationCode(phone);

            response.put("success", success);
            response.put("message", success ? "验证码发送成功" : "验证码发送失败");
            response.put("phone", phone);

            logger.info("验证码发送结果: {}, 手机号: {}", success, phone);
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            logger.error("发送验证码失败: {}", phone, e);
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @PostMapping("/login")
    @Operation(summary = "手机号登录", description = "使用手机号和验证码登录")
    public ResponseEntity<Map<String, Object>> login(
            @RequestParam String phone,
            @RequestParam String code) {

        logger.info("收到登录请求: {}, 验证码: {}", phone, code);
        Map<String, Object> response = new HashMap<>();

        try {
            if (!smsService.isValidPhone(phone)) {
                response.put("success", false);
                response.put("message", "手机号格式不正确");
                return ResponseEntity.badRequest().body(response);
            }

            // 验证验证码
            boolean valid = smsService.verifyCode(phone, code);
            if (!valid) {
                response.put("success", false);
                response.put("message", "验证码错误或已过期");
                logger.warn("验证码验证失败: {}", phone);
                return ResponseEntity.badRequest().body(response);
            }

            // 创建或获取用户并生成token
            String token = userService.loginOrRegister(phone);

            response.put("success", true);
            response.put("token", token);
            response.put("phone", phone);
            response.put("message", "登录成功");

            logger.info("用户登录成功: {}", phone);
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            logger.error("登录过程出错: {}", phone, e);
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @GetMapping("/check-phone")
    @Operation(summary = "检查手机号状态", description = "检查手机号格式和发送状态")
    public ResponseEntity<Map<String, Object>> checkPhoneStatus(
            @RequestParam String phone) {

        Map<String, Object> response = new HashMap<>();
        boolean isValid = smsService.isValidPhone(phone);
        boolean canSend = smsService.canSendCode(phone);
        long nextSendTime = smsService.getNextSendTime(phone);

        response.put("valid", isValid);
        response.put("canSend", canSend);
        response.put("nextSendTime", nextSendTime);
        response.put("message", isValid ?
                (canSend ? "可以发送验证码" : "请等待" + nextSendTime + "秒后再发送") :
                "手机号格式不正确");

        return ResponseEntity.ok(response);
    }
}